<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 系统用户管理控制器
 * @package App\Http\Controllers\Admin
 */
class SysUserController extends BaseController
{
    private $userSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->userSer = new \App\Services\SysUserService();
    }

    /**
     * 用户列表
     */
    public function index(Request $request)
    {
        if ($request->ajax()){
            $pageSize = $request->get('pageSize', 10);
            //状态条件
            $query = \App\Models\SysUser::select('*');
            $status = $request->input('status', -1);
            if ($status > -1){
                if ($status == 0){
                    $query->whereNull('deleted_at');
                }else{
                    $query->whereNotNull('deleted_at');
                }
            }
            //关键字
            $keyword = $request->get('keyword', '');
            if ($keyword){
                $query->where('name', 'like', '%'.$keyword.'%');
            }
            //DB::table('test')->paginate();
            $rows = $query->withTrashed()->paginate($pageSize);
            if ($rows){
                foreach ($rows as $k => $v){
                    $v['roles'] = $v->roles;
                    $v['roleIds'] = $v->roles()->get()->pluck('role_id')->toArray();
                    $rows[$k] = $v;
                }
            }
            //$queries = DB::getQueryLog();// 获取查询日志
            //print_r($queries);
            return $rows;
        }

        //角色列表数据
        $roleSer = new \App\Services\SysRoleService();
        $roleList = $roleSer->getRoleList();
        if ($roleList){
            foreach ($roleList as $k => $v){
                $v['is_opentree'] = true;
                $roleList[$k] = $v;
            }
        }
        //树结构用户组列表
        $tree          = new \App\Services\TreeService('role_id', 'parent_id', 'children');
        $tree->nameKey = 'display_name';
        $tree->load($roleList);
        $this->viewData['roleList'] = $tree->makeJsTreeFormat();

        return view('admin.sysuser.index', $this->viewData);
    }

    /**
     * 新建、编辑保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminSysUserPost $request)
    {
        try{
            if(!$this->userSer->save($request)){
                throw new \Exception('保存失败');
            }
            return $this->showMsg('success', '编辑成功');
        }catch (\Exception $e){
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 切换状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function changeStatus(Request $request){
        try{
            $userId = $request->input('id', 0);
            $status = $request->input('status', 0);
            if ($userId == 1 && $status == 0){
                throw new \Exception('超级管理员不允许禁用');
            }
            if(!$this->userSer->changestatus($userId, $status)){
                throw new \Exception('保存失败');
            }
            return $this->showMsg('success', '更改状态成功');
        }catch (\Exception $e){
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 保存用户权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function editRole(Request $request)
    {
        try {
            $userId = (int)$request->input('user_id', 0);
            if (!$userId) {
                throw new \Exception('请选择要设置角色的用户');
            }
            $roleIds = (array)$request->input('roleIds', []);
            $rs = $this->userSer->saveRole($userId, $roleIds);
            if ($rs) {
                return $this->showMsg('success', '设置用户角色成功',[], 'admin.sysuser.index');
            }
            throw new \Exception('设置用户角色失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
